package myJs.user

import myJs.Implicits.JArJDS
import myJs.Utils.{dataDismiss, filterDataField}
import myJs.myPkg.jquery.{$, JQuery}
import myJs.tool.Tool.getIds
import myJs.user.SampleManage.{getFilterDataFieldName, zeroFill}
import org.scalajs.dom.Element
import scalatags.Text.all._

import scala.scalajs.js.Date

/**
 * Created by yz on 3/6/2020
 */
trait SampleManageTool {

  def timeBefore = (dateStr: String, dbDateStr: String) => {
    val date = new Date(dateStr)
    val dbDate = new Date(dbDateStr)
    dbDate.setUTCHours(0, 0, 0, 0)
    date.getTime() <= dbDate.getTime()
  }

  def timeAfter = (dateStr: String, dbDateStr: String) => {
    val date = new Date(dateStr)
    val dbDate = new Date(dbDateStr)
    dbDate.setUTCHours(0, 0, 0, 0)
    date.getTime() >= dbDate.getTime()
  }

  def getFilterDataFieldName(y: Element) = {
    $(y).attr("filter-data-field").get
  }

  def bindEvt = {
    $("#table").on("check.bs.table", () => getIds)
    $("#table").on("uncheck.bs.table", () => getIds)
    $("#table").on("check-all.bs.table", () => getIds)
    $("#table").on("uncheck-all.bs.table", () => getIds)
    $("#table").on("page-change.bs.table", () => getIds)

  }

  def getTimeFilterData(y: Element, data: JArJDS, f: (String, String) => Boolean) = {
    val fiedlName = $(y).attr("filter-data-field").get
    val date = $(y).`val`().toString
    if (date.isEmpty) {
      data
    } else {
      data.filter { dict =>
        val dbDate = dict(fiedlName)
        f(date, dbDate)
      }
    }
  }

  def getInputFileterData(y: Element, data: JArJDS) = {
    val fiedlName = getFilterDataFieldName(y)
    val v = $(y).`val`().toString
    if (v.trim.isEmpty) {
      data
    } else {
      data.filter { dict =>
        val dbV = dict(fiedlName)
        dbV.contains(v)
      }
    }
  }

  def timeFormat(time: Date) = {
    val year = time.getFullYear()
    val month = time.getMonth().toInt + 1
    val day = time.getDate().toInt
    s"${year}-${zeroFill(month)}-${zeroFill(day)}"
  }

  def zeroFill(int: Int) = {
    if (int < 10) s"0${int}" else int.toString
  }



}
